package com.scst.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.scst.constant.MessageConstant;
import com.scst.dto.UserLoginDTO;
import com.scst.entity.User;
import com.scst.exception.LoginFailedException;
import com.scst.mapper.UserMapper;
import com.scst.properties.WeChatProperties;
import com.scst.service.UserService;
import com.scst.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper ;

    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type","authorization_code" );
        String json=HttpClientUtil.doGet(WX_LOGIN,map);

        JSONObject jsonObject= JSON.parseObject(json);
        String openid=jsonObject.getString("openid");
        //判断openid是否为空，是则抛出异常
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
         //判断当前用户是否为新用户
        User user=userMapper .getOpenId(openid);
        //如果是新用户，则自动完成注册
        if(user==null) {
           user= User.builder()
                   .openid(openid)
                   .createTime(LocalDateTime.now())
                   .build();
           userMapper .insert(user);
        }
        return user;
    }
}
